package com.jorado.metrics.type;

import com.jorado.metrics.util.LabelHelp;
import com.jorado.metrics.util.VersionHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public final class Counter {

    public static final Logger logger = LoggerFactory.getLogger(Counter.class);

    private ConcurrentHashMap<String, io.prometheus.client.Counter> COUNTERS = new ConcurrentHashMap<>(16);

    private static Counter INSTANCE = null;

    public static Counter getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Counter();
        }
        return INSTANCE;
    }

    public void register(String name, String help, String... labels) {
        if (COUNTERS.containsKey(name)) {
            logger.error("name of " + name + " is already exist, please try another one.");
        } else {
            help += VersionHelp.Ver;
            COUNTERS.put(name, io.prometheus.client.Counter.build().name(name).help(help).labelNames(LabelHelp.addLabels(labels)).register());
        }
    }

    public void inc(String name, String... labelValues) {
        inc(name, 1, labelValues);
    }

    public void inc(String name, double value, String... labelValues) {
        try {
            io.prometheus.client.Counter counter = COUNTERS.get(name);
            if (counter != null) {
                counter.labels(LabelHelp.addValues(labelValues)).inc(value);
            } else {
                logger.error("metrics counter is null. name: " + name);
            }
        } catch (Exception e) {
            logger.error("inc", e);
        }
    }

}
